import React, { useEffect, useRef } from 'react';
import useDrawPolyline from './useDrawPolyline';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { DrawProvider, useDrawStore } from './store';

const pathMenu = [
  {
    label: 'Street',
    color: '#cbcbcb',
    width: 20,
  },
  {
    label: 'Walking Path',
    color: '#b2b2b2',
    width: 3,
  },
];

const DrawPath = ({ id = 'path-layer1' }) => {
  const [createPolylineGraphic, updatePolylineGraphic] = useDrawPolyline({ id });
  const updateRef = useRef(updatePolylineGraphic);
  const [drawState, drawDispatch] = useDrawStore();
  const SimpleLineSymbolRef = useRef(null);

  useEffect(() => {
    init();

    return () => {
      drawDispatch({
        type: 'remove',
        payload: {
          id,
        },
      });
    };
  }, []);

  async function init() {
    const view = await viewUtils.isViewReady();
    const [SimpleLineSymbol] = await jsapi.load(['esri/symbols/SimpleLineSymbol']);
    SimpleLineSymbolRef.current = SimpleLineSymbol;
    drawDispatch({
      type: 'add',
      payload: {
        [id]: updatePolylineGraphic,
      },
    });
  }

  function handleDrawClick(item) {
    const symbol = new SimpleLineSymbolRef.current({
      color: item.color,
      width: item.width,
    });
    createPolylineGraphic(symbol, item.color);
    // .then(e => console.log('createPolylineGraphic then', e))
    // .catch(e => console.warn('createPolylineGraphic then', e));
  }

  return (
    <div
      style={{
        width: 100,
        height: 100,
        position: 'absolute',
        left: '50%',
        top: '50%',
        border: '1px solid red',
        color: 'red',
      }}
    >
      {pathMenu.map(item => {
        return (
          <p
            key={item.label}
            onClick={() => {
              handleDrawClick(item);
            }}
            style={{}}
          >
            {item.label}
          </p>
        );
      })}
    </div>
  );
};

export default DrawPath;
